<template>
	<view class="box">
		<u-empty    v-if="list.length==0&&status!='loadmore'"   text="当前无服务中"    icon="https://cdn.uviewui.com/uview/empty/history.png">
		</u-empty>
		<view v-else class="content2" v-for="(item, index) in list">
			<u-row customStyle="margin-bottom: 10px">
			    <u-col span="6">
			            <view class="demo-left" >
			            	预:<span style="color: red;">{{item.appointmentTime}} </span><!-- <span style="margin-left: 10px;">11km </span> -->
			    		</view>
			        </u-col>
			    	<u-col span="3">
			    		<view >
			    			<view class="typeName">
			    				{{item.serveName}}
			    			</view>
			    		</view>
			    	</u-col>
			        <u-col span="3">
			            <view class="demo-right"  >
							<span>{{(item.totalPrice/100).toFixed(2)}}元</span>
			            </view>
			    		<uview-ui>
			    			<u-divider></u-divider>
			    			<span></span>
			    		</uview-ui>
			        </u-col>
			    </u-row>
			    <u-steps  direction="column" dot activeColor="#ffd02b" inactiveColor="#00ac4e">
			    	<u-steps-item :title="'('+item.userName+')'+item.userAddress" :desc="item.address">
			    	</u-steps-item>
			    	<u-steps-item  :desc="getDistances(technicianlatitude,technicianlongitude,item.latitude,item.longitude)">
			    		
			    	</u-steps-item>
			    </u-steps>  
			    <view class="u-demo-block">
			    	备注：{{item.serviceRemark||" "}}<br/>
					已服务{{calculateTimeDifferenceInMinutes(new Date(item.serviceTime),new Date())}}分钟
					
			    	<!-- <u-read-more showHeight="40" :shadowStyle="shadowStyle" :toggle="true" fontSize="10px" closeText="展开备注">
			    		<rich-text :nodes="item.serviceRemark"></rich-text>
			    	</u-read-more> -->
			    </view>
				<view class="" >
					<u-row customStyle="margin-bottom: 10px">
						<u-col span="2">
							<view >
								<u-button icon="file-text" plain
							        type="primary" shape="circle"size="small" text="详情" @click="navigateTodetails(item.id)"
									  color="linear-gradient(to right, rgb(254, 223, 77), rgb(255, 211, 77))"
								></u-button>
							</view>
						</u-col>
						<u-col span="3">
							<view >
								<u-button icon="camera" plain
							        type="primary" shape="circle"size="small" text="服务中照" @click="ServicePhotos(item)"
									  color="linear-gradient(to right, rgb(254, 223, 77), rgb(255, 211, 77))"
								></u-button>
							</view>
						</u-col>
						<u-col span="7">
							<view class="btn2" style="margin-left: 10px;">
								<u-button  type="primary" shape="circle"size="small" text="完成拍照" @click="serviceComplete(item)"
									 color="linear-gradient(to right, rgb(254, 223, 77), rgb(255, 211, 77))"
								></u-button>
							</view>
						</u-col>
						<!-- <u-col span="4">
							<view class="btn2" style="margin-left: 10px;">
								<u-button type="primary" shape="circle"size="small" text="完成上传" @click="navigateTo(item)"
									 color="linear-gradient(to right, rgb(254, 223, 77), rgb(255, 211, 77))"
								></u-button>
							</view>
						</u-col> -->
						
					</u-row>
					
				</view>
			   
		
		</view>	
		<view >
			<u-popup :show="show" @close="close" @open="open"  :round="10"  >
			    <view class="bottom">
					<view class="fontweight">尾款设置</view>
					<uni-forms ref="valiForm"  :modelValue="form"  :rules="rules" label-width="80">
						<uni-forms-item label="订单总额:" >
							<uni-easyinput disabled v-model="form.zong" placeholder="金额获取异常" />
						</uni-forms-item>
						<uni-forms-item label="预约金额:"  >
							<uni-easyinput disabled v-model="form.pointmentMoneya" placeholder="金额获取异常" />
						</uni-forms-item>
						<uni-forms-item label="尾款金额:"  name="tailMoneya">
							<uni-easyinput @input="onInput" v-model="form.tailMoneya" placeholder="请输尾款金额" />
						</uni-forms-item>
						
					</uni-forms>
					<u-button type="primary" shape="circle"size="small" text="提交" @click="submit('valiForm')"
						 color="linear-gradient(to right, rgb(254, 223, 77), rgb(255, 211, 77))"
					></u-button>
			    </view>
			</u-popup>
		</view>
		<u-loadmore :status="status" v-if="list.length!=0"/>
	</view>
</template>

<script>
	import uEmpty from "@/pagesB/uview-ui/components/u-empty/u-empty";
	import uRow from "@/pagesB/uview-ui/components/u-row/u-row";
	import uCol from "@/pagesB/uview-ui/components/u-col/u-col";
	import uSteps from "@/pagesB/uview-ui/components/u-steps/u-steps";
	import uLoadmore from "@/pagesB/uview-ui/components/u-loadmore/u-loadmore";
	import uDivider from "@/pagesB/uview-ui/components/u-divider/u-divider";
	import {
	    mapState 
	} from 'vuex';
	export default {
		components: {
		    uEmpty,uRow,uCol,uSteps,uLoadmore,uDivider
		},
		data() {
			return {
				
				show: false,
				status: 'loadmore',//上滑加载函数
				technicianlatitude:"",
				technicianlongitude:"",
				list:[],
				pageVO:{
					pageNo: 1,
					pageSize: 10,
					technicianId:"", 
					receiveStatus:3,//技师接单状态（1未接单，2已接单，3服务中，4已完成，5拒绝接单，6取消）
					//orderStatus:1,//订单状态:1未接单 、2已接单、3服务中、4已经完成、5拒绝、6取消  
					sort:"desc",//排序
				},
				form:{
					zong:"20",
					pointmentMoneya:"20",
					tailMoneya:"",
				},
				details:"/pagesB/serviceList/details",
				mapid:{
					latitude:"25.267435438368057",
					longitude:"110.33772976345486",
				},
				shadowStyle: {
					    backgroundImage: "linear-gradient(-180deg, rgba(255, 255, 255, 0) 0%, #fff 80%)",
					    paddingTop: "30px",
					    marginTop: "-30px", 
				},				
				rules: {
					tailMoneya: {
						rules: [{	required: true,	errorMessage: '请输入尾款金额'}, 
					        	{format: 'number',    errorMessage: '请输入数字'},]
					},
					
				},
				datalist:{
					latitude:"",
					longitude:"",
					value3:"25.24188357813774",
					value4:"110.32012666223528 ",
					juli:"120.1121",
				}
			}
		},
		computed: {
			//获取是否登录
			...mapState(['userInfo']) 
		},
		mounted() {
			//获取当前位置 需用户授权  
			this.getCurrentLocal()
			this.showPage(true)
		},
		onShow() {
			//获取当前位置
		},
		
		methods: {
			//获取数据
			showPage(type){
				this.pageVO.technicianId=this.userInfo.id
				this.request.getRequest(this.http.httpsLian.orderDispatchRecord,this.pageVO, type)
				.then(res => { 
					console.log(res)
					this.status = 'nomore';
					if(res.code!=0 )return 
					if(res.data.list.length==0) {
					    this.status = 'nomore';
					    return
					}
					if(res.data.list.length<this.pageVO.pageSize) {
					    this.status = 'nomore';
					}
					if (this.pageVO.pageNo!= 1) {
						this.list = this.list.concat(res.data.list)
					} else {
						this.list=res.data.list
					} 
				}).catch(res => {
					uni.$u.toast(res)
				})
			},
			//服务拍照
			ServicePhotos(itme){
				console.log("服务拍照",itme)
				uni.navigateTo({
				   url: "/pagesB/serviceList/inServicePhotos?params="+encodeURIComponent(JSON.stringify(itme))
				});
			},
			updateStatus(type,itme){
				this.request.postRequest(this.http.httpsLian.orderDispatchRecordUpdateStatus+"?type="+type,{
					id:itme.id,
					technicianId:itme.technicianId,
					orderId:itme.orderId
				}, true)
				.then(res => { 
					let iconMsg;
					if(res.code==0)iconMsg=true;
					if(res.code!=0)iconMsg=false;
					//回复默认值
					this.list=[]
					this.pageVO.pageNo=1
					this.pageVO.pageSize=10
					this.showPage(false)
					uni.showToast({
						title:iconMsg?'提交成功':'提交失败',
						icon:iconMsg?"success":"error",
						duration: 1500
					})
				}).catch(res => {
					uni.$u.toast("网络异常6")
				})
			},
			onInput(newVal){
				this.form.zong=Number(this.form.pointmentMoneya)+Number(newVal)
				console.log('新数据',newVal)
				
			},
			//尾款金额提交
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					console.log('success', res);
					uni.showToast({
						title: `校验通过`
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
			open() {
			    // console.log('open');
			},
			close() {
			  this.show = false
			  // console.log('close');
			},
			//唤醒手机拨号
			getPhoneNumber(){
				uni.makePhoneCall({
				 	phoneNumber:'18978402266',
				 	 success(res) {
				 	 	console.log(res,'拨打成功')
				 	 }
				})
			},
			//主页index上拉事件触发 
			onReachBottomZ(){
				console.log('上拉事件触发');
				this.pageVO.pageNo+=1
				this.status = 'loading';
				this.showPage(true)
				this.$emit('onReachBottomZ')
			},
			//主页index 页面下拉时触发，与 onLoad 等生命周期函数平级
			onPullDownRefreshZ() {
				console.log('页面下拉时触发');
				this.status = 'loadmore';
				//回复默认值
				this.list=[]
				this.pageVO.pageNo=1
				this.pageVO.pageSize=10
				this.showPage(true)
			    setTimeout(() => {
					// 操作完成时，必须结束下拉刷新，否则一直会有 loading 标志
					uni.stopPullDownRefresh();
				}, 1000);
			},
			reload(){
				console.log('重新获取数据');
				this.status = 'loadmore';
				//回复默认值
				this.list=[]
				this.pageVO.pageNo=1
				this.pageVO.pageSize=10
				this.showPage(true)
			},
			//计算距离
			getDistances(la1, lo1, la2, lo2){
				return this.utils.getDistance(la1, lo1, la2, lo2)
			},
			// 获取当前地理位置 授权验证
			getCurrentLocal(){
			  let that = this;
			  wx.getSetting({
			    success(res) {
			      if (res.authSetting['scope.userLocation'] == false){// 如果已拒绝授权，则打开设置页面
			        wx.openSetting({
			          success(res) {}
			        })
			      }  else { // 第一次授权，或者已授权，直接调用相关api
			        that.getMyLocation()
			      }
			    }
			  })
			},
			// 获取当前地理位置
			getMyLocation(){
			    let that = this 
			    wx.getLocation({
			      type: 'gcj02',
			      success(res) {
			        console.log(res)
					that.technicianlatitude=res.latitude
					that.technicianlongitude=res.longitude
			      }
			    })
			},
			//判断跳转的页面
			
			//服务完成
			serviceComplete(item){
				//判断是否已经上传服务中的照片
				console.log("判断服务完成时间",item)
				console.log("判断服务完成时间S",item.workingAchievementPicUrl)
				if(item.workingAchievementPicUrl==null){
					uni.showModal({
					    title: '提示',
					    content: '请先上传服务中的照片，在点击完成服务！！',
					    showCancel: true, // 是否显示取消按钮
					    cancelText: '取消', // 取消按钮的文字，最多 4 个字符
					    confirmText: '确定', // 确认按钮的文字，最多 4 个字符
					    confirmColor: '#00ac4e', // 确认按钮的文字颜色
					    success: function (res) {
					       
					    }
					});
					return
				}
				
		
				let time= this.calculateTimeDifferenceInMinutes(new Date(item.serviceTime),new Date())
				console.log("判断服务完成时间",time)
				if(time<120){
					uni.showModal({
					    title: '提示',
					    content: '当前服务未到120分钟，是否确认完成服务？',
					    showCancel: true, // 是否显示取消按钮
					    cancelText: '取消', // 取消按钮的文字，最多 4 个字符
					    //cancelColor: '#000000', // 取消按钮的文字颜色
					    confirmText: '确定', // 确认按钮的文字，最多 4 个字符
					    confirmColor: '#00ac4e', // 确认按钮的文字颜色
					    success: function (res) {
					        if (res.confirm) {
					           uni.navigateTo({
					              url: '/pagesB/serviceList/inServicePhotosComplete?orderId='+item.orderId+'&&id='+item.id
					           });
					        } else if (res.cancel) {
					            console.log('用户点击取消');
					            // 执行其他操作
					        }
					    }
					});
					return
				}
				uni.navigateTo({
				   url: '/pagesB/serviceList/inServicePhotosComplete?orderId='+item.orderId+'&&id='+item.id
				});
			},
			//完成上传
			navigateTo(item) {
				//判断服务完成时间
				
				let time= this.calculateTimeDifferenceInMinutes(new Date(item.serviceTime),new Date())
				console.log("判断服务完成时间",time)
				if(time<120){
					uni.showModal({
					    title: '提示',
					    content: '当前服务未到120分钟，是否确认完成服务？',
					    showCancel: true, // 是否显示取消按钮
					    cancelText: '取消', // 取消按钮的文字，最多 4 个字符
					    //cancelColor: '#000000', // 取消按钮的文字颜色
					    confirmText: '确定', // 确认按钮的文字，最多 4 个字符
					    confirmColor: '#00ac4e', // 确认按钮的文字颜色
					    success: function (res) {
					        if (res.confirm) {
					           uni.navigateTo({
					              url: '/pagesB/serviceList/photograph?orderId='+item.orderId+'&&id='+item.id
					           });
					        } else if (res.cancel) {
					            console.log('用户点击取消');
					            // 执行其他操作
					        }
					    }
					});
					return
				}
				uni.navigateTo({
				   url: '/pagesB/serviceList/photograph?orderId='+item.orderId+'&&id='+item.id
				}); 
				
			},
			navigateTodetails(ids){
				/* uni.navigateTo({
				   url: "/pagesB/serviceList/details?id="+id
				}); */
				uni.navigateTo({
				   url: "/pagesB/serviceList/details?params="+encodeURIComponent(JSON.stringify({id:ids}))
				});
			},
			//计算用时分钟
			calculateTimeDifferenceInMinutes(startTimeStr, endTimeStr) {
			    // 将时间字符串转换为Date对象
			    const startTime = new Date(startTimeStr);
			    const endTime = new Date(endTimeStr);
			 
			    // 计算两个时间点之间的差值（毫秒）
			    const timeDifference = endTime - startTime;
			 
			    // 将差值从毫秒转换为分钟
			    const minutesDifference = timeDifference / (1000 * 60);
			 
			    return Math.round(minutesDifference);
			}

		}
	}
</script>

<style lang="scss" scoped>
	
.box{
	//padding: 10px;
}	
.content2{
	
	background-color: white;
	padding: 8px ;
	//margin-top: 10px;
	margin-bottom: 10px;
	border-radius: 4px;
	.demo-right {
		text-align: right;
		span{
			color: red;
		}
	}
	.demo-left{
		color: $uni-text-color-placeholder;
	}
	.demo-left,.demo-right{
		font-size: 13px;
		
	}
	/deep/.u-text__value--main{
		font-size: 18px !important;
	}
	/deep/.u-text__value--tips{
		font-size: 14px !important;
	}

	/deep/.u-steps-item__content {
		margin-bottom: 10rpx;
		
	}
	/deep/.u-steps-item__line {
		height: 90px;
	}
	.slot-icon{
		font-size: 20upx;
	}
	/deep/.u-button{
	   
	    color: black !important;
		margin-top: 10px;
		margin-bottom: 5px;
	}
}
.typeName{
	border-radius: 2px;
	background-color: #fff6f5;
	//width:100rpx;
	font-size: 25rpx;
	padding: 7rpx;
	color:red;
	display: inline-block;
	position: relative;
	/* top:-33px;
	 left: 70px; */
}
.u-demo-block{
	font-size: 13px;
	color: $uni-text-color-placeholder;
	/deep/.u-read-more__content {
		font-size: 13px;
        color: $uni-text-color-placeholder;
	}
	/deep/.u-text__value{
		color: $Main-green-color !important;
	}
	margin-bottom: 10rpx;
}
.fontweight{
	font-weight: 550;
}
.bottom{
	padding: 10px;
	/deep/.u-button{
	   
	    color: black !important;
		margin-top: 30px;
		margin-bottom: 5px;
	}
	/deep/.u-input{
		width: 120px !important;
		//background-color: rgb(245, 247, 250);
	 
	}
	/deep/.is-input-border{
		width:220px;
	}
	.fontweight{
		margin-bottom: 20px;
	}
}
</style>
